<?php
namespace Api\Controller;
use Think\Controller;
class LoginController extends BaseController {

    //***************************
    //  获取sessionkey 接口
    //***************************
    public function getsessionkey(){
//        $wx_config['appid'] = 'wx52d9daaf6007119b';
//        $wx_config['secret'] ='7be67d60c5105815c4bf516e60da8f8f';
        $wx_config['appid'] = 'wxd7648f7f2dd9d952';
        $wx_config['secret'] ='36577aef3d0710a3ff31c60681b1cc3d';
//        $wx_config = C('weixin');
        $appid = $wx_config['appid'];
        $secret = $wx_config['secret'];
        $code = trim($_REQUEST['code']);

        $name = $_REQUEST['name'];
        $sex = $_REQUEST['gender'];
        if(!$sex){
            $sex = '未知';
        }else{
            $sex = '1' ? '男' : '女';
        }

        if(!$name){
            $name = '匿名用户';
        }

        if (!$code) {
            echo json_encode(array('status'=>0,'err'=>'非法操作！'));
            exit();
        }

        if (!$appid || !$secret) {
            echo json_encode(array('status'=>0,'err'=>'非法操作！'.__LINE__));
            exit();
        }

        $get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_token_url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
//        $a = get_object_vars($res);
        if($res){
            $b = json_decode($res);
            $open_id = $b->openid;
            $data['open_id'] = $open_id;
            $data['sex'] = $sex;
            $data['name'] = $name;
            //查询用户是否注册过，如果没有，就添加一个新的数据
            $user = M('user');
            $list = $user->where("open_id = '$open_id'")->select();
            if(!$list){
                $user->add($data);
                $b->type = 2;
                echo json_encode($b);
            }else{
                $b->type = 1;
                echo json_encode($b);
            }
        }
        exit();
    }





}
